import React, { Component } from 'react'
// 受控组件
// 表单项中的值它受到state数据来进行控制，并且还要通过onChange事件来对state数据进行修改
//  value/checked  onChange
// react中表单数所的收集，它没有像vue中的v-model

class App extends Component {
  lessons = ['html', 'css', 'js', 'vue', 'react', '鸿蒙']
  state = {
    uname: '',
    isChecked: false,
    selectedLessons: [],
    sex: '1',
    city: 0
  }
  setUname = e => {
    const value = e.target.value
    this.setState({ uname: value })
  }
  setChecked = e => {
    let isChecked = e.target.checked
    let selectedLessons = []
    if (isChecked) {
      selectedLessons = this.lessons
    }
    this.setState({ isChecked, selectedLessons })
  }
  // 选中
  selectedLessonHandle = item => e => {
    const checked = e.target.checked
    // 勾选中时才添加
    if (checked) {
      this.setState(state => ({
        selectedLessons: [...state.selectedLessons, item]
      }))
    } else {
      this.setState(state => ({
        selectedLessons: state.selectedLessons.filter(val => val != item)
      }))
    }
  }

  setSex = e => {
    this.setState({ sex: e.target.value })
  }
  setCity = e => {
    // console.log(typeof e.target.value)
    this.setState({ city: Number(e.target.value) })
  }

  loginHandle = () => {
    console.log(this.state)
  }

  render() {
    const { uname, isChecked, selectedLessons, sex, city } = this.state

    return (
      <div>
        <div>
          账号：
          <input type='text' value={uname} onChange={this.setUname} />
        </div>
        <div>
          <input type='checkbox' checked={isChecked} onChange={this.setChecked} />
        </div>
        <div>
          <ul>
            {this.lessons.map((item, index) => (
              <li key={index}>
                <input
                  type='checkbox'
                  value={item}
                  checked={selectedLessons.includes(item)}
                  onChange={this.selectedLessonHandle(item)}
                />
                <span>{item}</span>
              </li>
            ))}
          </ul>
        </div>
        <div>
          <label>
            <input type='radio' value='1' checked={sex === '1'} onChange={this.setSex} />男
          </label>
          <label>
            <input type='radio' value='2' checked={sex === '2'} onChange={this.setSex} />女
          </label>
        </div>
        <div>
          <select value={city} onChange={this.setCity}>
            <option value={0}>请选择</option>
            <option value={1}>北京</option>
            <option value={2}>上海</option>
          </select>
        </div>
        <br />
        <div>
          <button onClick={this.loginHandle}>进入系统</button>
        </div>
      </div>
    )
  }
}

export default App
